package servlet;

import model.User;
import service.FavoriteService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 取消收藏的Servlet
 */
@WebServlet(name = "favorite_delete", urlPatterns = "/favorite_delete")
public class FavoriteDeleteServlet extends HttpServlet {
    private FavoriteService favoriteService = new FavoriteService();

    /**
     * 处理取消收藏商品的请求
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取商品ID
        int goods_id = Integer.parseInt(request.getParameter("goodsid"));
        
        // 从session中获取用户信息
        User user = (User) request.getSession().getAttribute("user");
        if (user == null) {
            // 用户未登录，跳转到登录页面
            response.sendRedirect("user_login.jsp");
            return;
        }
        
        // 取消收藏
        favoriteService.deleteFavorite(user.getId(), goods_id);
        
        // 获取来源URL，判断是从详情页来的还是从收藏列表来的
        String from = request.getParameter("from");
        if ("list".equals(from)) {
            // 从收藏列表来的，返回收藏列表
            response.sendRedirect("favorite_list");
        } else {
            // 从商品详情页来的，返回商品详情页
            response.sendRedirect("goods_detail?id=" + goods_id);
        }
    }
} 